import util, { isReallyNull } from '../common/util'
import { Token } from '../storage/index'
import { baseURL } from './config'

const http = {
  showLoading: true,
  baseConfig: {
    header: {
      'content-type': 'application/json'
    },
    dataType: 'json',
    method: 'GET'
  },
  get: (url, data, loading) => {
    const reqconfig = { ...http.baseConfig }
    reqconfig.url = url
    reqconfig.method = 'GET'
    reqconfig.data = data
    return http.request(reqconfig, loading)
  },
  post: (url, data, loading) => {
    const reqconfig = { ...http.baseConfig }
    reqconfig.url = url
    reqconfig.method = 'POST'
    reqconfig.data = data
    return http.request(reqconfig, loading)
  },
  request: (config, loading) => {
    const reqconfig = { ...http.baseConfig, ...config }
    reqconfig.url = baseURL + reqconfig.url
    const token = Token.Get()
    if (!isReallyNull(token)) {
      reqconfig.header['x-auth-token'] = token
    }
    reqconfig.method = reqconfig.method.toUpperCase()
    const hideLoadingFun = () => {
      if (isReallyNull(loading) || loading) {
        uni.hideLoading()
      }
    }
    if (isReallyNull(loading) || loading) {
      uni.showLoading({
        title: '加载中...',
        mask: true
      })
    }
    return new Promise((resolve, reject) => {
      if (reqconfig.success || reqconfig.fail || reqconfig.complete) {
        let completeFun = () => {}
        if (reqconfig.complete !== undefined) {
          completeFun = reqconfig.complete
        }
        const tempcompletefun = () => {
          hideLoadingFun()
          completeFun()
        }
        uni.request({ ...reqconfig, finally: tempcompletefun })
      } else {
        uni.request(reqconfig)
          .then(res => {
            if (res.length > 0) {
              // res[1].statusCode
              resolve(res[1].data)
            } else {
              resolve({ success: false })
            }
          })
          .catch(err => {
            reject(err)
          })
          .finally(hideLoadingFun)
      }
    })
  }
}

export default http
